package com.wangyadong.hobby.schedule.jobtask.dsa.stack;

import javax.swing.plaf.synth.SynthOptionPaneUI;
import java.util.Stack;

public class MatchHtml {

    private static final char STARTING = '<';
    private static final char CLOSEING = '>';
    private static final Stack stack = new Stack();

    private static final String html = "<body>" +
            "<center>" +
            "<h1> The Little Boat </h1>" +
            "</center>" +
            "<p> The storm tossed the little" +
            "boat like a cheap sneaker in an" +
            "old washing machine. The three" +
            "drunken fishermen were used to" +
            "such treatment, of course, but" +
            "not the tree salesman, who even as" +
            "a stowaway now felt that he" +
            "had overpaid for the voyage. </p>" +
            "<ol>" +
            "<li> Will the salesman die? </li>" +
            "<li> What color is the boat? </li>" +
            "<li> And what about Naomi? </li>" +
            "</ol>" +
            "</body>";

    public static boolean isMatched(String html) {
        int index = html.indexOf(STARTING);
//        while (index != -1) {
//            int endIndex = html.indexOf(CLOSEING, index + 1);
//            if (endIndex == -1) {
//                return false;
//            }
//            endIndex = html.indexOf(STARTING, endIndex + 1);
//            if (endIndex == -1) {
//                return false;
//            }
//            String tag = html.substring(endIndex+1, html.indexOf(CLOSEING, endIndex + 1));
//            if (tag.startsWith("/")) {
//                if(stack.isEmpty()){
//                    return false;
//                }
//                if (!stack.pop().equals(tag.substring(1))) {
//                    return false;
//                }
//            } else {
//                stack.push(tag);
//            }
//            index = endIndex + 1;
//    }

        int startIndex = html.indexOf(STARTING);
        while (startIndex != -1) {
            int endIndex = html.indexOf(CLOSEING, startIndex);
            if (endIndex == -1) {
                return false;
            }
            String tag = html.substring(startIndex+1, endIndex);
            if (tag.startsWith("/")) {
                if (stack.isEmpty()) {
                    return false;
                }
                if (!stack.pop().equals(tag.substring(1))) {
                    return false;
                }
            } else {
                stack.push(tag);
            }
            startIndex = html.indexOf(STARTING, endIndex + 1);
        }
        return stack.isEmpty();
    }


    public static void main(String[] args) {
//        int i = html.indexOf(STARTING, 1);
//        System.out.println(i);
        boolean matched = isMatched(html);
        System.out.println(matched);
    }
}
